package impl

import (
	"context"
	"fmt"

	"gitee.com/zatto/project/devcloud/mcenter/apps/user"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func (i *impl) CreateUser(ctx context.Context, in *user.CreateUserRequest) (*user.User, error) {
	// 创建用户实例
	ins, err := user.New(in)
	if err != nil {
		return nil, err
	}

	// 写入数据库
	_, err = i.col.InsertOne(ctx, ins)
	if err != nil {
		return nil, err
	}

	// 返回用户实例
	return ins, nil
}

func (i *impl) UpdateUser(ctx context.Context, in *user.UpdateUserRequest) (*user.User, error) {
	return nil, fmt.Errorf("not implement")
}

func (i *impl) DeleteUser(ctx context.Context, in *user.DeleteUserRequest) (*user.User, error) {
	return nil, fmt.Errorf("not implement")
}

// 查询用户列表
func (i *impl) QueryUser(ctx context.Context, in *user.QueryUserRequest) (*user.UserSet, error) {
	set := user.NewUserSet()
	// 构建查询条件
	filter := bson.M{}
	if in.Keywords != "" {
		filter["username"] = bson.M{"$regex": in.Keywords, "$options": "im"}
	}
	opts := &options.FindOptions{}
	opts.SetLimit(int64(in.Page.PageSize))
	opts.SetSkip(in.Page.ComputeOffset())

	cursor, err := i.col.Find(ctx, filter, opts)
	if err != nil {
		return nil, err
	}

	// 执行查询sql
	for cursor.Next(ctx) {
		ins := user.NewDefaultUser()
		if err := cursor.Decode(ins); err != nil {
			return nil, err
		}

		// 密码显示为****
		ins.Desense()
		// 加入到集合
		set.Add(ins)
	}

	// 统计总数
	set.Total, err = i.col.CountDocuments(ctx, filter)
	if err != nil {
		return nil, err
	}

	return set, nil
}

func (i *impl) DescribeUser(ctx context.Context, in *user.DescribeUserRequest) (*user.User, error) {
	// 构建查询条件
	filter := bson.M{}
	switch in.DescribeBy {
	case user.DESCRIBE_BY_USER_ID:
		filter["_id"] = in.DescribeValue
	case user.DESCRIBE_BY_USERNAME:
		filter["username"] = in.DescribeValue
	}

	// 执行查询sql
	ins := user.NewDefaultUser()
	err := i.col.FindOne(ctx, filter).Decode(ins)
	if err != nil {
		return nil, err
	}

	return ins, err
}
